package top.chukongxiang.project.base.oauth2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import top.chukongxiang.project.base.exception.oauth2.MyWebResponseExceptionTranslator;
import top.chukongxiang.project.base.oauth2.provider.cas.CasTokenGranter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 授权服务器配置
 * @author 楚孔响
 * @version 1.0
 * @date 2021/12/14 17:15
 */
@Configuration
@EnableAuthorizationServer
@DependsOn("authWebSecurityConfig")
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisTokenStore redisTokenStore;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Autowired
    ServiceProperties serviceProperties;

    @Bean
    public TokenEnhancer tokenEnhancer() {
        return new TokenJwtEnhancer();
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {

//        jwt添加自定义信息
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), jwtAccessTokenConverter));

        endpoints
                .tokenGranter(tokenGranter(endpoints))
                .tokenStore(redisTokenStore)
                .tokenEnhancer(tokenEnhancerChain)
                // oauth/token 认证异常处理
                .exceptionTranslator(new MyWebResponseExceptionTranslator())
//                .allowedTokenEndpointRequestMethods(HttpMethod.GET)
//                .tokenEnhancer(jwtAccessTokenConverter)
                .authenticationManager(authenticationManager);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().withClient("dfyj")
                    .secret(passwordEncoder.encode("123456789"))
                .accessTokenValiditySeconds(3600 * 12)
                .refreshTokenValiditySeconds(3600 * 24)
                // 支持的授权模式：刷新token，授权码模式，password模式
                .authorizedGrantTypes("refresh_token", "authorization_code", "password", CasTokenGranter.GRANT_TYPE)
//                .redirectUris("http://authserver.dfyj.com/oauth")
                .scopes("all");
    }


    /**
     * 使用自定义的tokenGranter方法，添加自定义的granter
     */
    private TokenGranter tokenGranter(final AuthorizationServerEndpointsConfigurer endpoints) {
        // 获取默认的granter集合
        List<TokenGranter> granters = new ArrayList<>(Collections.singletonList(endpoints.getTokenGranter()));
        granters.add(CasTokenGranter.builder()
                .authenticationManager(authenticationManager)
                .serviceProperties(serviceProperties)
                .authorizationServerTokenServices(endpoints.getTokenServices())
                .clientDetailsService(endpoints.getClientDetailsService())
                .oAuth2RequestFactory(endpoints.getOAuth2RequestFactory())
                .build());
        return new CompositeTokenGranter(granters);
    }
}
